#include "UART_4G.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "ti_msp_dl_config.h"

#define RX_BUFFER_SIZE 256

// UART接收缓冲区和相关变量
static char g_rx_buffer[RX_BUFFER_SIZE];
static volatile uint16_t g_rx_index = 0;
static volatile int g_brace_count = 0; // 用于跟踪JSON花括号

static UART_4G_DataCallback g_data_callback = NULL;


/**
 * @brief 初始化4G模块驱动
 */
void UART_4G_Init(void)
{
    // 清空缓冲区和状态
    memset(g_rx_buffer, 0, sizeof(g_rx_buffer));
    g_rx_index = 0;
    g_brace_count = 0;
    
    g_data_callback = NULL;

    // 仅使能接收中断
    DL_UART_Main_enableInterrupt(UART_4G_GPS_INST, DL_UART_MAIN_INTERRUPT_RX);
    DL_UART_Main_disableInterrupt(UART_4G_GPS_INST, DL_UART_MAIN_INTERRUPT_TX);
}

/**
 * @brief 注册一个回调函数，用于处理接收到的数据
 */
void UART_4G_SetDataCallback(UART_4G_DataCallback callback)
{
    g_data_callback = callback;
}


/**
 * @brief 通过4G模块发送字符串 (阻塞版本)
 * @note 此函数将阻塞直到所有数据被发送出去。
 */
void UART_4G_SendString(const char *str)
{
    if (!str) return;
    
    while (*str) {
        // 使用TI官方的阻塞式发送函数，确保每个字节都被发送
        DL_UART_Main_transmitDataBlocking(UART_4G_GPS_INST, *str++);
    }
}

/**
 * @brief UART接收处理函数, 在中断中调用 (JSON模式)
 */
void UART_4G_IRQHandler(void)
{
    uint8_t rx_data = DL_UART_Main_receiveData(UART_4G_GPS_INST);

    if (rx_data == '{') {
        if (g_brace_count == 0) {
            g_rx_index = 0;
        }
        g_brace_count++;
    }

    if (g_brace_count > 0) {
        if (g_rx_index < (RX_BUFFER_SIZE - 1)) {
            g_rx_buffer[g_rx_index++] = rx_data;
        } else {
            // 缓冲区溢出，重置以等待下一次有效消息
            g_rx_index = 0;
            g_brace_count = 0;
        }
    }

    if (rx_data == '}') {
        g_brace_count--;
        if (g_brace_count == 0 && g_rx_index > 0) {
            g_rx_buffer[g_rx_index] = '\0';
            if (g_data_callback != NULL) {
                g_data_callback(g_rx_buffer);
            }
            g_rx_index = 0; // 重置以备下次使用
        } else if (g_brace_count < 0) {
            // 花括号不匹配，可能是干扰数据，重置
            g_brace_count = 0;
            g_rx_index = 0;
        }
    }
} 